<template>
  <div class="add-process-container">
    <div class="page-header">
      <h2>修改工艺流程</h2>
    </div>
    
    <div class="form-content">
      <!-- 基础信息 -->
      <div class="section">
        <div class="section-title">基础信息</div>
        <el-form :model="editForm" label-width="120px" class="add-form" :rules="formRules" ref="formRef">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工艺流程编号" prop="processCode">
                <div class="code-input-group">
                  <el-input 
                    v-model="editForm.processCode" 
                    :disabled="editForm.useSystemCode" 
                    placeholder="请输入工艺流程编号"
                    @change="handleProcessCodeChange"
                  />
                  <el-checkbox 
                    v-model="editForm.useSystemCode" 
                    style="margin-left: 10px;"
                    @change="handleSystemCodeChange"
                  >
                    系统编号
                  </el-checkbox>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工艺流程名称">
                <el-input v-model="editForm.processName" placeholder="请输入工艺流程名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人">
                <el-select v-model="editForm.responsibleName" placeholder="选择负责人" style="width: 100%;">
                  <el-option 
                    v-for="person in personList" 
                    :key="person.id" 
                    :label="person.name" 
                    :value="person.name" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门">
                <el-cascader
                  v-model="editForm.departmentPath"
                  :options="departmentList"
                  :props="cascaderProps"
                  placeholder="请选择部门"
                  style="width: 100%;"
                  @change="handleDepartmentChange"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态">
                <el-select v-model="editForm.processStatus" style="width: 100%;">
                  <el-option label="启用" :value="1" />
                  <el-option label="禁用" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input 
                  v-model="editForm.processRemark" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入备注信息" 
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 加工工序 -->
      <div class="section">
        <div class="section-title">加工工序</div>
        <div class="process-buttons">
          <el-button type="primary" @click="addProcess">添加</el-button>
          <el-button @click="removeProcess">移除</el-button>
        </div>
        <el-table :data="editForm.processList" class="process-table" :border="true" :stripe="true">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="加工工序" width="100" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="processCode" label="工序编码" width="120" align="center" />
          <el-table-column prop="processName" label="工序名称" width="180" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button link type="primary" @click="moveProcessUp(scope.$index)" :disabled="scope.$index === 0">上移</el-button>
              <el-button link type="primary" @click="moveProcessDown(scope.$index)" :disabled="scope.$index === editForm.processList.length - 1">下移</el-button>
              <el-button link type="danger" @click="removeProcessRow(scope.$index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 附件 -->
      <div class="section">
        <div class="section-title">附件</div>
        <div class="attachment-section">
          <div class="attachment-left">
            <div v-if="editForm.attachments.length === 0" class="no-files">
              暂无附件
            </div>
            <div v-else>
              <div v-for="(attachment, index) in editForm.attachments" :key="index" class="file-item">
                <div class="file-info">
                  <div class="file-name" @click="previewFile(attachment)" :title="attachment.fileName">
                    {{ attachment.fileName }}
                  </div>
                  <div class="file-details">
                    <div>文件大小：{{ formatFileSize(attachment.fileSize) }}</div>
                    <div>上传时间：{{ attachment.uploadTime }}</div>
                  </div>
                </div>
                <div class="file-actions">
                  <el-button link type="primary" @click="updateFile(index)">更新上传</el-button>
                  <el-button link type="danger" @click="deleteFile(index)">删除</el-button>
                </div>
              </div>
            </div>
          </div>
          <div class="attachment-right">
            <el-upload
              class="upload-area"
              drag
              :action="''"
              multiple
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="false"
              :accept="'.pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg,.txt'">
              <div class="upload-content">
                <el-icon class="upload-icon"><UploadFilled /></el-icon>
                <div>点击上传 / 拖拽到此区域</div>
                <div class="upload-hint">支持 PDF、Word、Excel、图片等格式</div>
                <div class="upload-buttons">
                  <el-button type="primary" size="small" @click="handleBatchUpload">批量上传</el-button>
                </div>
              </div>
            </el-upload>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="form-footer">
        <el-button @click="handleCancel">关闭</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </div>

    <!-- 添加工序对话框 -->
    <el-dialog 
      v-model="addProcessDialog.visible" 
      title="添加工序" 
      width="800px"
      :close-on-click-modal="false"
      class="add-process-dialog">
      <div class="dialog-content">
        <!-- 已选选项标签 -->
        <div class="selected-tag">
          <span>已选选项</span>
        </div>
        
        <!-- 搜索框 -->
        <div class="search-section">
          <el-input 
            v-model="addProcessDialog.searchText" 
            placeholder="请搜索"
            suffix-icon="Search"
            style="width: 300px;"
            @input="handleSearch" />
        </div>

        <!-- 工序列表表格 -->
        <el-table 
          :data="addProcessDialog.filteredProcessList" 
          ref="processTableRef"
          @selection-change="handleSelectionChange"
          :border="true" 
          :stripe="true"
          v-loading="addProcessDialog.loading"
          style="margin-top: 20px;">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ (addProcessDialog.currentPage - 1) * addProcessDialog.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="processCode" label="工序编码" width="120" align="center" />
          <el-table-column prop="processName" label="工序名称" min-width="180" />
          <el-table-column prop="responsiblePerson" label="负责人" width="120" align="center" />
          <el-table-column prop="departmentName" label="所属部门" width="150" align="center" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <div class="pagination-info">
            共 {{ addProcessDialog.total }} 项数据
          </div>
          <el-pagination
            v-model:current-page="addProcessDialog.currentPage"
            v-model:page-size="addProcessDialog.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="addProcessDialog.total"
            layout="sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="pagination-controls" />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAddProcess">取消</el-button>
          <el-button type="primary" @click="confirmAddProcess">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import type { UploadFile } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { getPersons, getDepartments, getProcessList, uploadFile as apiUploadFile, uploadFiles as apiUploadFiles, updateProcessFlow, getProcessFlowDetailById } from '@/Https/server';

const router = useRouter();
const route = useRoute();

// 获取路由参数中的ID
const processFlowId = route.params.id as string;

// 定义工序列表项接口
interface ProcessListItem {
  processCode: string;
  processName: string;
}

// 定义负责人接口
interface PersonItem {
  id: number;
  name: string;
  employeeNumber: string;
  department: string;
  position: string;
}

// 定义部门接口
interface DepartmentItem {
  values: number;
  label: string;
  url?: string;
  children?: DepartmentItem[];
}

// 定义工序表接口
interface ProcessTableItem {
  id: number;
  processCode: string;
  processName: string;
  responsiblePerson: string;
  departmentName: string;
  description?: string;
  isEnabled?: boolean;
  createTime?: string;
  updateTime?: string;
  updateName?: string;
}

// 定义附件接口
interface AttachmentItem {
  id?: number;
  fileName: string;
  fileSize: number;
  uploadTime: string;
  fileUrl?: string;
}

// 负责人列表数据
const personList = ref<PersonItem[]>([]);
// 部门列表数据
const departmentList = ref<DepartmentItem[]>([]);

// 获取负责人列表
const getPersonList = async () => {
  try {
    const response: any = await getPersons();
    if (response.code == 200) {
      personList.value = response.data;
    }
  } catch (error) {
    console.error('获取负责人列表失败:', error);
    ElMessage.error('获取负责人列表失败');
  }
};

// 级联选择器配置
const cascaderProps = {
  value: 'values',
  label: 'label',
  children: 'children',
  checkStrictly: false,
  emitPath: false
};

// 获取部门列表
const getDepartmentList = async () => {
  try {
    const response: any = await getDepartments();
    if (response.code == 200) {
      departmentList.value = response.data;
    }
  } catch (error) {
    console.error('获取部门列表失败:', error);
    ElMessage.error('获取部门列表失败');
  }
};

// 获取工序列表
const getProcessTableList = async () => {
  try {
    addProcessDialog.loading = true;
    const response: any = await getProcessList({
      ProcessName: addProcessDialog.searchText || '',
      PageIndex: addProcessDialog.currentPage,
      PageSize: addProcessDialog.pageSize
    });
    if (response.code == 200) {
      addProcessDialog.processList = response.pageData || [];
      addProcessDialog.total = response.totalCount || 0;
      updateFilteredList();
    }
  } catch (error) {
    console.error('获取工序列表失败:', error);
    ElMessage.error('获取工序列表失败');
  } finally {
    addProcessDialog.loading = false;
  }
};

// 根据部门ID获取部门路径
const getDepartmentPathById = (departmentId: number): any[] => {
  const findPath = (list: DepartmentItem[], targetId: number): any[] => {
    for (const item of list) {
      if (item.values === targetId) {
        return [targetId];
      }
      if (item.children && item.children.length > 0) {
        const childPath = findPath(item.children, targetId);
        if (childPath.length > 0) {
          return [item.values, ...childPath];
        }
      }
    }
    return [];
  };
  
  return findPath(departmentList.value, departmentId);
};

// 根据负责人ID获取负责人姓名
const getResponsibleNameById = (responsibleId: number): string => {
  const person = personList.value.find(p => p.id === responsibleId);
  return person ? person.name : '';
};

// 处理部门选择变化
const handleDepartmentChange = (value: any) => {
  if (value && value.length > 0) {
    // 找到选中的部门节点
    const findDepartmentName = (list: DepartmentItem[], targetValue: any): string => {
      for (const item of list) {
        if (item.values === targetValue) {
          return item.label;
        }
        if (item.children && item.children.length > 0) {
          const result = findDepartmentName(item.children, targetValue);
          if (result) return result;
        }
      }
      return '';
    };
    
    const selectedValue = Array.isArray(value) ? value[value.length - 1] : value;
    editForm.departmentName = findDepartmentName(departmentList.value, selectedValue);
  } else {
    editForm.departmentName = '';
  }
};

// 获取工艺流程详情
const getProcessFlowDetail = async () => {
  try {
    // 验证ID是否存在
    if (!processFlowId) {
      ElMessage.error('工艺流程ID无效');
      router.back();
      return;
    }

    const loading = ElLoading.service({
      lock: true,
      text: '正在加载数据...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 调用API获取工艺流程详情
    const response: any = await getProcessFlowDetailById({ 
      processFlowId: processFlowId 
    });
    
    console.log('工艺流程详情API响应:', response);
    
    if (response && response.code === 200 && response.data) {
      const data = response.data;
      console.log('工艺流程详情数据:', data);
      console.log('工序操作数据:', data.processOperations || data.ProcessOperations || data.operations);
      
      // 填充基础信息
      await fillBasicInfo(data);
      
      // 填充工序信息
      await fillProcessOperations(data);
      
      // 填充附件信息
      await fillAttachments(data);
      
      ElMessage.success('工艺流程数据加载成功');
    } else {
      const errorMsg = response?.message || response?.msg || '获取工艺流程详情失败';
      ElMessage.error(errorMsg);
      console.error('API返回错误:', response);
      router.back();
    }
    
    loading.close();
  } catch (error: any) {
    console.error('获取工艺流程详情异常:', error);
    const errorMessage = error?.response?.data?.message || error?.message || '获取工艺流程详情失败，请重试';
    ElMessage.error(errorMessage);
    console.error('详细错误信息:', error?.response?.data || error);
    // 注释掉自动返回，让用户能看到错误信息
    // router.back();
  }
};

// 填充基础信息
const fillBasicInfo = async (data: any) => {
  try {
    // 基础字段填充
    editForm.id = data.id || 0;
    editForm.processCode = data.processCode || data.ProcessCode || '';
    editForm.processName = data.processName || data.ProcessName || '';
    editForm.processStatus = data.processStatus !== undefined ? data.processStatus : (data.ProcessStatus !== undefined ? data.ProcessStatus : 1);
    editForm.processRemark = data.processRemark || data.ProcessRemark || data.remark || data.Remark || '';
    editForm.useSystemCode = false; // 编辑时默认不使用系统编号
    
    // 处理负责人信息
    if (data.responsibleId || data.ResponsibleId) {
      const responsibleId = data.responsibleId || data.ResponsibleId;
      editForm.responsibleName = getResponsibleNameById(responsibleId);
    } else if (data.responsibleName || data.ResponsibleName) {
      editForm.responsibleName = data.responsibleName || data.ResponsibleName;
    }
    
    // 处理部门信息
    if (data.departmentId || data.DepartmentId) {
      const departmentId = data.departmentId || data.DepartmentId;
      editForm.departmentPath = getDepartmentPathById(departmentId);
      editForm.departmentName = data.departmentName || data.DepartmentName || '';
    } else if (data.departmentName || data.DepartmentName) {
      editForm.departmentName = data.departmentName || data.DepartmentName;
    }
    
    console.log('基础信息填充完成:', {
      id: editForm.id,
      processCode: editForm.processCode,
      processName: editForm.processName,
      responsibleName: editForm.responsibleName,
      departmentName: editForm.departmentName,
      processStatus: editForm.processStatus,
      processRemark: editForm.processRemark
    });
  } catch (error) {
    console.error('填充基础信息错误:', error);
    ElMessage.warning('基础信息填充异常，请检查数据');
  }
};

// 填充工序信息
const fillProcessOperations = async (data: any) => {
  try {
    // 清空现有工序列表
    editForm.processList = [];
    
    // 处理工序操作数据
    const operations = data.processOperations || data.ProcessOperations || data.operations || [];
    
    if (Array.isArray(operations) && operations.length > 0) {
      editForm.processList = operations.map((operation: any, index: number) => ({
        processCode: operation.operationCode || operation.OperationCode || operation.processCode || operation.ProcessCode || operation.processId || '',
        processName: operation.operationName || operation.OperationName || operation.processName || operation.ProcessName || ''
      }));
      
      console.log(`成功填充 ${editForm.processList.length} 个工序:`, editForm.processList);
    } else {
      console.log('未找到工序数据或工序数据为空');
    }
    
    // 触发表单验证
    if (formRef.value) {
      setTimeout(() => {
        formRef.value?.validateField('processList');
      }, 100);
    }
  } catch (error) {
    console.error('填充工序信息错误:', error);
    ElMessage.warning('工序信息填充异常，请检查数据');
  }
};

// 填充附件信息
const fillAttachments = async (data: any) => {
  try {
    // 清空现有附件列表
    editForm.attachments = [];
    
    // 处理附件数据
    const attachments = data.attachments || data.Attachments || data.files || [];
    
    if (Array.isArray(attachments) && attachments.length > 0) {
      editForm.attachments = attachments.map((attachment: any) => ({
        id: attachment.id || attachment.Id,
        fileName: attachment.filename || attachment.fileName || attachment.FileName || attachment.name || '',
        fileSize: attachment.filesize || attachment.fileSize || attachment.FileSize || attachment.size || 0,
        uploadTime: attachment.createTime || attachment.CreateTime || attachment.uploadTime || attachment.UploadTime || formatTime(new Date()),
        fileUrl: attachment.filepath || attachment.filePath || attachment.FilePath || attachment.url || attachment.fileUrl || ''
      }));
      
      console.log(`成功填充 ${editForm.attachments.length} 个附件:`, editForm.attachments);
    } else {
      console.log('未找到附件数据或附件数据为空');
    }
  } catch (error) {
    console.error('填充附件信息错误:', error);
    ElMessage.warning('附件信息填充异常，请检查数据');
  }
};

onMounted(async () => {
  // 先加载基础数据
  await Promise.all([
    getPersonList(),
    getDepartmentList()
  ]);
  
  // 然后加载工艺流程详情
  await getProcessFlowDetail();
});

// 编辑表单数据
const editForm = reactive({
  id: 0,
  processCode: '',
  useSystemCode: false,
  processName: '',
  responsibleName: '',
  departmentName: '',
  departmentPath: [] as any[],
  processStatus: 1,
  processRemark: '',
  processList: [] as ProcessListItem[],
  attachments: [] as AttachmentItem[]
});

// 添加工序对话框数据
const addProcessDialog = reactive({
  visible: false,
  searchText: '',
  loading: false,
  processList: [] as ProcessTableItem[],
  filteredProcessList: [] as ProcessTableItem[],
  currentPage: 1,
  pageSize: 5,
  total: 0,
  selectedProcesses: [] as ProcessTableItem[]
});

// 表单验证规则
const formRules = {
  processCode: [
    { required: true, message: '请输入工艺流程编号', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  processName: [
    { required: true, message: '请输入工艺流程名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  responsibleName: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ],
  departmentPath: [
    { type: 'array', required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  processStatus: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  processList: [
    { type: 'array', required: true, message: '请添加至少一个加工工序', trigger: 'change' }
  ]
};

// 表单引用
const formRef = ref<any>(null);

// 辅助函数：根据负责人姓名获取ID
const getResponsibleIdByName = (name: string): number | null => {
  const person = personList.value.find(p => p.name === name);
  return person ? person.id : null;
};

// 辅助函数：根据部门路径获取部门ID
const getDepartmentIdByPath = (path: any[]): number | null => {
  if (!path || path.length === 0) return null;
  const selectedValue = Array.isArray(path) ? path[path.length - 1] : path;
  return selectedValue;
};

// 辅助函数：根据工序编码获取工序ID
const getOperationIdByCode = (code: string): number | null => {
  const operation = addProcessDialog.processList.find((p: ProcessTableItem) => p.processCode === code);
  return operation ? operation.id : null;
};

// 取消按钮
const handleCancel = () => {
  router.back();
}

// 确定按钮
const handleConfirm = async () => {
  try {
    // 表单验证
    const valid = await formRef.value?.validate();
    if (!valid) {
      ElMessage.error('请检查表单填写是否正确');
      return;
    }

    // 数据完整性检查
    if (!validateFormData()) {
      return;
    }

    // 显示加载状态
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交修改...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    try {
      // 准备提交数据
      const submitData = prepareSubmitData();
      console.log('提交数据:', submitData);

      // 调用修改API
      const response: any = await updateProcessFlow(submitData);
      console.log('修改API响应:', response);
      
      if (response && (response.code === 200 || response.success)) {
        ElMessage.success('修改工艺流程成功');
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          router.back();
        }, 1000);
      } else {
        const errorMsg = response?.message || response?.msg || response?.error || '修改工艺流程失败';
        ElMessage.error(errorMsg);
        console.error('修改失败:', response);
      }
    } finally {
      loading.close();
    }
  } catch (error) {
    console.error('修改工艺流程异常:', error);
    ElMessage.error('修改工艺流程失败，请重试');
  }
};

// 验证表单数据完整性
const validateFormData = (): boolean => {
  // 检查基础信息
  if (!editForm.processCode || !editForm.processCode.trim()) {
    ElMessage.error('请输入工艺流程编号');
    return false;
  }

  if (!editForm.processName || !editForm.processName.trim()) {
    ElMessage.error('请输入工艺流程名称');
    return false;
  }

  if (!editForm.responsibleName || !editForm.responsibleName.trim()) {
    ElMessage.error('请选择负责人');
    return false;
  }

  if (!editForm.departmentPath || editForm.departmentPath.length === 0) {
    ElMessage.error('请选择所属部门');
    return false;
  }

  // 检查是否添加了工序
  if (editForm.processList.length === 0) {
    ElMessage.warning('请至少添加一个加工工序');
    return false;
  }

  // 验证负责人ID
  const responsibleId = getResponsibleIdByName(editForm.responsibleName);
  if (!responsibleId) {
    ElMessage.error('选择的负责人无效，请重新选择');
    return false;
  }

  // 验证部门ID
  const departmentId = getDepartmentIdByPath(editForm.departmentPath);
  if (!departmentId) {
    ElMessage.error('选择的部门无效，请重新选择');
    return false;
  }

  return true;
};

// 准备提交数据
const prepareSubmitData = () => {
  // 获取负责人ID和部门ID
  const responsibleId = getResponsibleIdByName(editForm.responsibleName);
  const departmentId = getDepartmentIdByPath(editForm.departmentPath);

  // 构建提交数据结构
  const submitData = {
    // 基础信息
    Id: editForm.id,
    ProcessCode: editForm.processCode.trim(),
    ProcessName: editForm.processName.trim(),
    ResponsibleId: responsibleId,
    DepartmentId: departmentId,
    ProcessStatus: editForm.processStatus,
    ProcessRemark: editForm.processRemark.trim(),
    UpdateName: '当前用户', // TODO: 从用户登录信息中获取实际用户名
    
    // 工序操作
    ProcessOperations: editForm.processList.map((item, index) => {
      const operationId = getOperationIdByCode(item.processCode);
      return {
        OperationId: operationId || 0, // 如果找不到ID则设为0
        OperationCode: item.processCode,
        OperationName: item.processName,
        Sequence: index + 1,
        Remark: ''
      };
    }),
    
    // 附件信息
    Attachments: editForm.attachments.map((item, index) => ({
      Id: item.id || 0,
      Filename: item.fileName,
      Filepath: item.fileUrl || '',
      Filesize: item.fileSize,
      Sequence: index + 1
    }))
  };

  return submitData;
};

// 处理工艺流程编号变化
const handleProcessCodeChange = (value: string) => {
  if (value) {
    editForm.processCode = value.trim();
  }
  // 触发表单验证
  formRef.value?.validateField('processCode');
};

// 处理系统编号选择变化
const handleSystemCodeChange = (value: boolean) => {
  if (value) {
    // 选择系统编号时，生成系统编号格式
    editForm.processCode = generateSystemCode();
  } else {
    // 取消系统编号时，清空编号让用户手动输入
    editForm.processCode = '';
  }
  // 触发表单验证
  formRef.value?.validateField('processCode');
};

// 生成系统编号
const generateSystemCode = (): string => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const time = String(now.getHours()).padStart(2, '0') + String(now.getMinutes()).padStart(2, '0');
  
  // 生成格式: PF + 年月日 + 时分 + 随机数
  const random = Math.floor(Math.random() * 100).toString().padStart(2, '0');
  return `PF${year}${month}${day}${time}${random}`;
};

// 添加工序
const addProcess = () => {
  addProcessDialog.visible = true;
  addProcessDialog.searchText = '';
  addProcessDialog.currentPage = 1;
  addProcessDialog.pageSize = 5;
  addProcessDialog.selectedProcesses = [];
  // 打开对话框时加载数据
  getProcessTableList();
}

// 更新过滤后的列表
const updateFilteredList = () => {
  // 对于动态加载的数据，直接使用processList，因为后端已经处理了搜索和分页
  addProcessDialog.filteredProcessList = addProcessDialog.processList;
};

// 移除工序
const removeProcess = () => {
  ElMessage.info('请选择要移除的工序');
}

// 移除指定工序行
const removeProcessRow = (index: number) => {
  editForm.processList.splice(index, 1);
  // 触发表单验证
  formRef.value?.validateField('processList');
}

// 上移工序
const moveProcessUp = (index: number) => {
  if (index > 0) {
    const temp = editForm.processList[index];
    editForm.processList[index] = editForm.processList[index - 1];
    editForm.processList[index - 1] = temp;
  }
}

// 下移工序
const moveProcessDown = (index: number) => {
  if (index < editForm.processList.length - 1) {
    const temp = editForm.processList[index];
    editForm.processList[index] = editForm.processList[index + 1];
    editForm.processList[index + 1] = temp;
  }
}

// 搜索工序
const handleSearch = () => {
  addProcessDialog.currentPage = 1;
  getProcessTableList();
};

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  addProcessDialog.pageSize = val;
  addProcessDialog.currentPage = 1;
  getProcessTableList();
};

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  addProcessDialog.currentPage = val;
  getProcessTableList();
};

// 处理工序选择变化
const handleSelectionChange = (selection: ProcessTableItem[]) => {
  addProcessDialog.selectedProcesses = selection;
};

// 取消添加工序
const cancelAddProcess = () => {
  addProcessDialog.visible = false;
  addProcessDialog.selectedProcesses = [];
};

// 确认添加工序
const confirmAddProcess = () => {
  if (addProcessDialog.selectedProcesses.length === 0) {
    ElMessage.warning('请选择要添加的工序');
    return;
  }
  
  // 检查是否有重复的工序
  const existingCodes = editForm.processList.map((item: ProcessListItem) => item.processCode);
  const duplicates = addProcessDialog.selectedProcesses.filter((process: ProcessTableItem) => 
    existingCodes.includes(process.processCode)
  );
  
  if (duplicates.length > 0) {
    ElMessage.warning(`工序 ${duplicates.map((d: ProcessTableItem) => d.processCode).join(', ')} 已存在，请勿重复添加`);
    return;
  }
  
  // 记录添加的数量
  const addedCount = addProcessDialog.selectedProcesses.length;
  
  // 添加选中的工序
  addProcessDialog.selectedProcesses.forEach((process: ProcessTableItem) => {
    editForm.processList.push({
      processCode: process.processCode,
      processName: process.processName
    });
  });
  
  addProcessDialog.visible = false;
  addProcessDialog.selectedProcesses = [];
  ElMessage.success(`成功添加 ${addedCount} 个工序`);
  
  // 触发表单验证
  formRef.value?.validateField('processList');
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 格式化时间
const formatTime = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 处理文件选择变化
const handleFileChange = async (uploadFile: UploadFile) => {
  if (!uploadFile.raw) return;
  
  try {
    // 显示上传中消息
    ElMessage.info('正在上传文件...');
    
    // 调用单文件上传API
    const response: any = await apiUploadFile(uploadFile.raw);
    
    if (response) {
      // 添加到附件列表
      const newAttachment: AttachmentItem = {
        fileName: uploadFile.name,
        fileSize: uploadFile.size || 0,
        uploadTime: formatTime(new Date()),
        fileUrl: response // 后端返回的文件URL
      };
      
      editForm.attachments.push(newAttachment);
      ElMessage.success(`文件 "${uploadFile.name}" 上传成功`);
    } else {
      ElMessage.error('文件上传失败');
    }
  } catch (error) {
    console.error('文件上传错误:', error);
    ElMessage.error('文件上传失败，请重试');
  }
};

// 更新文件
const updateFile = (index: number) => {
  // 创建隐藏的文件输入元素
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg,.txt';
  
  input.onchange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    
    if (!file) return;
    
    try {
      // 显示上传中消息
      ElMessage.info('正在更新文件...');
      
      // 调用单文件上传API
      const response: any = await apiUploadFile(file);
      
      if (response) {
        // 更新附件信息
        editForm.attachments[index] = {
          fileName: file.name,
          fileSize: file.size,
          uploadTime: formatTime(new Date()),
          fileUrl: response
        };
        
        ElMessage.success(`文件更新成功`);
      } else {
        ElMessage.error('文件更新失败');
      }
    } catch (error) {
      console.error('文件更新错误:', error);
      ElMessage.error('文件更新失败，请重试');
    }
  };
  
  input.click();
};

// 删除文件
const deleteFile = (index: number) => {
  const fileName = editForm.attachments[index].fileName;
  editForm.attachments.splice(index, 1);
  ElMessage.success(`文件 "${fileName}" 已删除`);
};

// 批量上传文件
const handleBatchUpload = () => {
  // 创建隐藏的文件输入元素
  const input = document.createElement('input');
  input.type = 'file';
  input.multiple = true;
  input.accept = '.pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg,.txt';
  
  input.onchange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const files = Array.from(target.files || []);
    
    if (files.length === 0) return;
    
    try {
      // 显示上传中消息
      ElMessage.info(`正在批量上传 ${files.length} 个文件...`);
      
      // 调用批量文件上传API
      const response: any = await apiUploadFiles(files);
      
      if (response) {
        // 解析返回的URL字符串（逗号分隔）
        const urls = response.split(',');
        
        // 为每个文件添加到附件列表
        files.forEach((file, index) => {
          const newAttachment: AttachmentItem = {
            fileName: file.name,
            fileSize: file.size,
            uploadTime: formatTime(new Date()),
            fileUrl: urls[index] || response // 使用对应的URL或整个响应
          };
          editForm.attachments.push(newAttachment);
        });
        
        ElMessage.success(`成功上传 ${files.length} 个文件`);
      } else {
        ElMessage.error('批量文件上传失败');
      }
    } catch (error) {
      console.error('批量文件上传错误:', error);
      ElMessage.error('批量文件上传失败，请重试');
    }
  };
  
  input.click();
};

// 预览文件
const previewFile = (attachment: AttachmentItem) => {
  if (attachment.fileUrl) {
    // 在新窗口中打开文件
    window.open(attachment.fileUrl, '_blank');
  } else {
    ElMessage.warning('文件URL不存在，无法预览');
  }
};
</script>

<style scoped>
.add-process-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.form-content {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.section {
  margin-bottom: 40px;
}

.section:last-child {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
  color: #303133;
}

.add-form {
  margin-bottom: 20px;
}

.code-input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.process-buttons {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.process-table {
  margin-bottom: 20px;
}

.attachment-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.attachment-left {
  flex: 1;
}

.attachment-right {
  flex: 1;
}

.file-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.file-info {
  margin-bottom: 10px;
}

.file-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.file-name:hover {
  color: #66b1ff;
}

.file-details {
  font-size: 12px;
  color: #909399;
}

.file-details div {
  margin-bottom: 2px;
}

.file-actions {
  display: flex;
  gap: 10px;
}

.upload-area {
  width: 100%;
  height: 120px;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 10px;
  color: #c0c4cc;
}

.upload-hint {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 5px;
}

.no-files {
  text-align: center;
  color: #909399;
  padding: 40px 20px;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.upload-buttons {
  margin-top: 15px;
}

.upload-buttons .el-button {
  margin: 0 5px;
}

.form-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 30px;
  border-top: 1px solid #e4e7ed;
  margin-top: 30px;
}

/* Element Plus 样式覆盖 */
:deep(.el-form-item__label) {
  color: #606266;
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-upload-dragger) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  width: 100%;
  height: 120px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fafafa;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}

/* 添加工序对话框样式 */
.add-process-dialog {
  .dialog-content {
    padding: 0;
  }

  .selected-tag {
    background-color: #f0f9ff;
    border: 1px solid #409eff;
    border-radius: 4px;
    padding: 8px 12px;
    margin-bottom: 20px;
    display: inline-block;
  }

  .selected-tag span {
    color: #409eff;
    font-size: 14px;
    font-weight: 500;
  }

  .search-section {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }

  .pagination-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding: 10px 0;
  }

  .pagination-info {
    font-size: 14px;
    color: #606266;
  }

  .pagination-controls {
    display: flex;
    align-items: center;
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 15px;
  }
}

/* 对话框内表格样式 */
:deep(.add-process-dialog .el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.add-process-dialog .el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

:deep(.add-process-dialog .el-table td) {
  padding: 8px 0;
}

/* 对话框内分页样式 */
:deep(.add-process-dialog .el-pagination) {
  justify-content: flex-end;
}

:deep(.add-process-dialog .el-pagination .el-select .el-input) {
  width: 100px;
}

:deep(.add-process-dialog .el-pagination .btn-next),
:deep(.add-process-dialog .el-pagination .btn-prev) {
  background-color: #f4f4f5;
  color: #606266;
}

:deep(.add-process-dialog .el-pagination .btn-next:disabled),
:deep(.add-process-dialog .el-pagination .btn-prev:disabled) {
  color: #c0c4cc;
}

:deep(.add-process-dialog .el-pagination .el-pager li.is-active) {
  background-color: #409eff;
  color: #ffffff;
}

:deep(.add-process-dialog .el-pagination .el-pager li:hover) {
  color: #409eff;
}

/* 对话框头部样式 */
:deep(.add-process-dialog .el-dialog__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 24px 16px;
}

:deep(.add-process-dialog .el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

:deep(.add-process-dialog .el-dialog__body) {
  padding: 20px 24px;
}

:deep(.add-process-dialog .el-dialog__footer) {
  padding: 16px 24px 20px;
  border-top: 1px solid #e4e7ed;
  background-color: #fafafa;
}
</style> 